﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Mvc;
using DHQGHN.PM2.Models;
using DHQGHN.PM2.Models.Online;
using DHQGHN.PM2.ViewModels;
using System.Reflection;
using System.Runtime.InteropServices;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Drawing;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Style;
using ICSharpCode.SharpZipLib.Core;
using DHQGHN.PM2.Security;
using System.Web.Configuration;

namespace DHQGHN.PM2.Controllers
{
    [Authorize]
    public class EnumeratorController : BaseController
    {
        public const int AddMode = 0;
        public const int UpdateMode = 1;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(EnumeratorController));
        public ActionResult Index()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[102] = "active";
                ViewBag.ActiveMenus[108] = "active";

                ViewBag.Groups = GetGroup();
                ViewBag.UpdateMode = AddMode;
                ViewBag.AdminCode = MyUser.AdminCode;

                return View();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [ValidateInput(false)]
        public ActionResult SearchAdmin(string AdminCode, string ENUM_CODE,
                        string FULL_NAME, string USERNAME, string GROUPCODE, int? page)
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            ViewBag.ActiveMenus[102] = "active";
            ViewBag.ActiveMenus[122] = "active";

            List<EnumeratorModel> objList = new List<EnumeratorModel>();

            if (MyUser.GroupCode == "AM")
            {
                GROUPCODE = "AT";
                ListTinh();
            }
            else if (MyUser.GroupCode == "AT")
            {
                ListHuyen();
                if (AdminCode == null)
                {
                    GROUPCODE = "AH";
                    AdminCode = MyUser.AdminCode;
                }
                else
                {
                    GROUPCODE = "AH";
                }
            }
            else if (MyUser.GroupCode == "AH" && AdminCode == null)
            {
                ListXa();
                if (AdminCode == null)
                {
                    GROUPCODE = "AX";
                    AdminCode = MyUser.AdminCode;
                }
                else
                    GROUPCODE = "AX";
            }
            try
            {
                EnumeratorSearchModel searchInfo = new EnumeratorSearchModel(AdminCode, ENUM_CODE, FULL_NAME, USERNAME, GROUPCODE);
                if (page == null)
                    searchInfo.PAGE_INDEX = "0";
                else
                    searchInfo.PAGE_INDEX = (page - 1).ToString();
                searchInfo.PAGE_SIZE = "10";
                ViewData["searchInfo"] = searchInfo;

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "SearchPagingForAdmin");
                    wc.Encoding = Encoding.UTF8;
                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    var jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(searchInfo);
                    string jsonResult = wc.UploadString(enumeratorServiceUrl + "SearchPagingForAdmin", "POST", jsonString);
                    objList = JsonConvert.DeserializeObjectAsync<List<EnumeratorModel>>(jsonResult).Result;
                    GetGroupCaption(objList);
                }

                if (page != 0 && objList.Count == 0)
                {
                    searchInfo.PAGE_INDEX = "0";
                    using (WebClient wc = new WebClient())
                    {
                        Helper.SetHeaderInfo(wc, "SearchPagingForAdmin");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        var jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(searchInfo);
                        string jsonResult = wc.UploadString(enumeratorServiceUrl + "SearchPagingForAdmin", "POST", jsonString);
                        objList = JsonConvert.DeserializeObjectAsync<List<EnumeratorModel>>(jsonResult).Result;
                        GetGroupCaption(objList);
                    }
                }
                if (AdminCode != null)
                {
                    if (AdminCode.Length >= 2)
                        ViewBag.Level1 = AdminCode.Substring(0, 2);
                    if (AdminCode.Length >= 5)
                        ViewBag.Level2 = AdminCode.Substring(0, 5);
                    if (AdminCode.Length == 10)
                        ViewBag.Level3 = AdminCode.Substring(0, 10);
                }
                else
                {
                    ViewBag.Level1 = null;
                    ViewBag.Level2 = null;
                    ViewBag.Level3 = null;
                }
                GetListDVHC(ViewBag.Level1, ViewBag.Level2, ViewBag.Level3);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return View(objList);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SearchAdminPost(string AdminCode, string ENUM_CODE,
                       string FULL_NAME, string USERNAME, string GROUPCODE, int? page)
        {
            try
            {
                return RedirectToAction("SearchAdmin", new
                {
                    AdminCode,
                    ENUM_CODE,
                    FULL_NAME,
                    USERNAME,
                    GROUPCODE,
                    page
                });
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return Content("Có lỗi xảy ra trong quá trình xử lý", "text/html", UTF8Encoding.UTF8);
            }
        }

        #region Create Admin Tinh
        [HttpGet]
        public ActionResult CreateAdminTinh()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[102] = "active";
                ViewBag.ActiveMenus[122] = "active";
                ListTinh();
                return PartialView();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult CreateAdminTinh(EnumeratorModel obj)
        {
            obj.GROUPCODE = "AT";
            if (obj.ADM_CODE.Length == 2)
            {
                string AdminCode = obj.ADM_CODE;
                string ENUM_CODE = obj.ENUM_CODE;
                string FULL_NAME = obj.FULL_NAME;
                string USERNAME = obj.USERNAME;
                string GROUPCODE = obj.GROUPCODE;
                string EnumID = obj.ENUMERATOR_ID;
                List<EnumeratorModel> objList = new List<EnumeratorModel>();
                try
                {
                    using (WebClient wc = new WebClient())
                    {
                        if (ModelState.IsValid)
                        {
                            MemoryStream ms = new MemoryStream();
                            Helper.SetHeaderInfo(wc, "AddEnumerator");
                            DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));

                            serializeUpload.WriteObject(ms, obj);
                            wc.Headers["Content-type"] = "application/json; charset=utf-8";
                            wc.UploadData(enumeratorServiceUrl + "AddEnumerator", "POST", ms.ToArray());
                            SaveUserNameToDBAdmin(GetData(obj, "A"), wc);

                            LogStream.Write(MyUser.UserName,
                                CommonData.AppName,
                                GetFunction(),
                                "Tạo quản trị tỉnh - CreateAdminTinh", obj);
                            ms.Dispose();
                        }

                        return Json("Tạo mới thành công", JsonRequestBehavior.AllowGet);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw ex;
                }
            }
            else
            {
                return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
            }

        }
        #endregion

        #region Create Admin Huyen
        [HttpGet]
        public ActionResult CreateAdminHuyen()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[102] = "active";
                ViewBag.ActiveMenus[122] = "active";
                ListHuyen();
                return PartialView();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult CreateAdminHuyen(EnumeratorModel obj, int? page)
        {
            try
            {
                obj.GROUPCODE = "AH";
                if (obj.ADM_CODE.Length == 5)
                {
                    string mtp = obj.ADM_CODE.Substring(0, 2);
                    string mtp2 = obj.ADM_CODE.Substring(2, 3);
                    string areaDownload;
                    if (mtp == MyUser.AdminCode)
                    {
                        using (WebClient wc = new WebClient())
                        {
                            Helper.SetHeaderInfo(wc, "Checkadminunit");
                            wc.Encoding = Encoding.UTF8;
                            //List<ResidentDetailViewModel> residentList = null;
                            //List<SelectListItem> lstItems = new List<SelectListItem>();
                            string UrlPath = string.Format("{0}{1}", enumeratorServiceUrl, "Checkadminunit" + "/" + mtp2 + "/" + mtp + "/" + "2");
                            areaDownload = wc.DownloadString(UrlPath);

                            //return bReturn;
                        }
                        if (areaDownload == "1")
                        {
                            string ENUM_CODE = obj.ENUM_CODE;
                            string FULL_NAME = obj.FULL_NAME;
                            string USERNAME = obj.USERNAME;
                            string GROUPCODE = obj.GROUPCODE;
                            string EnumID = obj.ENUMERATOR_ID;
                            List<EnumeratorModel> objList = new List<EnumeratorModel>();
                            try
                            {
                                using (WebClient wc = new WebClient())
                                {
                                    if (ModelState.IsValid)
                                    {
                                        Helper.SetHeaderInfo(wc, "AddEnumerator");
                                        MemoryStream ms = new MemoryStream();
                                        DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));

                                        serializeUpload.WriteObject(ms, obj);
                                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                                        wc.UploadData(enumeratorServiceUrl + "AddEnumerator", "POST", ms.ToArray());
                                        SaveUserNameToDBAdmin(GetData(obj, "A"), wc);

                                        LogStream.Write(MyUser.UserName,
                                            CommonData.AppName,
                                            GetFunction(),
                                            "Tạo quản trị huyện - CreateAdminHuyen", obj);
                                        ms.Dispose();
                                    }
                                    return Json("Tạo mới thành công", JsonRequestBehavior.AllowGet);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        else
                        {
                            return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
                        }
                    }
                    else
                    {
                        return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        #region Create Admin Xa
        [HttpGet]
        public ActionResult CreateAdmin()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[102] = "active";
                ViewBag.ActiveMenus[122] = "active";
                ListXa();
                return PartialView();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult CreateAdmin(EnumeratorModel obj, int? page)
        {
            try
            {
                obj.GROUPCODE = "AX";
                if (obj.ADM_CODE.Length == 10)
                {
                    string mtp = obj.ADM_CODE.Substring(0, 5);
                    string mtp2 = obj.ADM_CODE.Substring(5);
                    string areaDownload;
                    if (mtp == MyUser.AdminCode)
                    {
                        using (WebClient wc = new WebClient())
                        {
                            Helper.SetHeaderInfo(wc, "Checkadminunit");
                            wc.Encoding = Encoding.UTF8;
                            //List<ResidentDetailViewModel> residentList = null;
                            //List<SelectListItem> lstItems = new List<SelectListItem>();
                            string UrlPath = string.Format("{0}{1}", enumeratorServiceUrl, "Checkadminunit" + "/" + mtp2 + "/" + mtp.Substring(2) + "/" + "3");
                            areaDownload = wc.DownloadString(UrlPath);

                            //return bReturn;
                        }
                        if (areaDownload == "1")
                        {
                            ViewBag.Groups = GetGroup();
                            string AdminCode = obj.ADM_CODE;
                            string ENUM_CODE = obj.ENUM_CODE;
                            string FULL_NAME = obj.FULL_NAME;
                            string USERNAME = obj.USERNAME;
                            string GROUPCODE = obj.GROUPCODE;
                            string EnumID = obj.ENUMERATOR_ID;
                            List<EnumeratorModel> objList = new List<EnumeratorModel>();
                            try
                            {
                                using (WebClient wc = new WebClient())
                                {
                                    if (ModelState.IsValid)
                                    {
                                        Helper.SetHeaderInfo(wc, "AddEnumerator");
                                        MemoryStream ms = new MemoryStream();
                                        DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));

                                        serializeUpload.WriteObject(ms, obj);
                                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                                        wc.UploadData(enumeratorServiceUrl + "AddEnumerator", "POST", ms.ToArray());
                                        SaveUserNameToDBAdmin(GetData(obj, "A"), wc);

                                        LogStream.Write(MyUser.UserName,
                                            CommonData.AppName,
                                            GetFunction(),
                                            "Tạo quản trị xã - CreateAdmin", obj);
                                        ms.Dispose();
                                    }

                                    return Json("Tạo mới thành công", JsonRequestBehavior.AllowGet);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        else
                        {
                            return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
                        }
                    }
                    else
                    {
                        return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json("Có lỗi trong quá trình xử lý dữ liệu", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        #region Edit Admin Xa
        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public ActionResult EditAdmin(string EnumID)
        {
            try
            {
                EnumeratorModel obj = GetElementBy(EnumID);
                if (obj.ADM_CODE != null)
                {
                    if (obj.ADM_CODE.Length >= 2)
                        ViewBag.Level1x = obj.ADM_CODE.Substring(0, 2);
                    if (obj.ADM_CODE.Length >= 5)
                        ViewBag.Level2x = obj.ADM_CODE.Substring(0, 5);
                    if (obj.ADM_CODE.Length == 10)
                        ViewBag.Level3x = obj.ADM_CODE.Substring(0, 10);
                    obj.GROUP_CODE_OLD = obj.GROUPCODE;


                }
                else
                {
                    ViewBag.Level1x = null;
                    ViewBag.Level2x = null;
                    ViewBag.Level3x = null;
                }
                GetListDVHC(ViewBag.Level1x, ViewBag.Level2x, ViewBag.Level3x);
                return PartialView(obj);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult EditAdmin(EnumeratorModel obj)
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[102] = "active";
                ViewBag.ActiveMenus[122] = "active";
                obj.GROUPCODE = "AX";
                //ViewBag.Groups = GetGroup();
                if (obj.ADM_CODE.Length == 10)
                {
                    string mtp = obj.ADM_CODE.Substring(0, 5);
                    if (mtp == MyUser.AdminCode)
                    {

                        string mtp2 = obj.ADM_CODE.Substring(5);
                        string areaDownload;

                        using (WebClient wc = new WebClient())
                        {
                            Helper.SetHeaderInfo(wc, "Checkadminunit");
                            wc.Encoding = Encoding.UTF8;
                            //List<ResidentDetailViewModel> residentList = null;
                            //List<SelectListItem> lstItems = new List<SelectListItem>();
                            string UrlPath = string.Format("{0}{1}", enumeratorServiceUrl, "Checkadminunit" + "/" + mtp2 + "/" + mtp.Substring(2) + "/" + "3");
                            areaDownload = wc.DownloadString(UrlPath);

                            //return bReturn;
                        }
                        if (areaDownload == "1")
                        {

                            string AdminCode = obj.ADM_CODE;
                            string ENUM_CODE = obj.ENUM_CODE;
                            string FULL_NAME = obj.FULL_NAME;
                            string USERNAME = obj.USERNAME;
                            string GROUPCODE = obj.GROUPCODE;
                            try
                            {
                                using (WebClient wc = new WebClient())
                                {
                                    if (ModelState.IsValid)
                                    {
                                        Helper.SetHeaderInfo(wc, "EditEnumerator");
                                        MemoryStream ms = new MemoryStream();
                                        DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));

                                        serializeUpload.WriteObject(ms, obj);
                                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                                        wc.UploadData(enumeratorServiceUrl + "EditEnumerator", "POST", ms.ToArray());

                                        //UpdateUserGroup(GetData(obj, "A"), wc);
                                        UpdateGroup(GetData(obj, "A"), wc);
                                        UpdateUser(GetData(obj, "A"), wc);

                                        LogStream.Write(MyUser.UserName,
                                           CommonData.AppName,
                                           GetFunction(),
                                           "Cập nhật quản trị xã - EditAdmin", obj);
                                        ms.Dispose();
                                    }

                                    return Json("Tạo mới thành công", JsonRequestBehavior.AllowGet);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        else
                        {
                            return Json("Có lỗ trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                        }
                    }
                    else
                    {
                        return Json("Có lỗ trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json("Có lỗ trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        #region Edit Admin Huyen
        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public ActionResult EditAdminHuyen(string EnumID)
        {
            try
            {
                EnumeratorModel obj = GetElementBy(EnumID);
                if (obj.ADM_CODE != null)
                {
                    if (obj.ADM_CODE.Length >= 2)
                        ViewBag.Level1h = obj.ADM_CODE.Substring(0, 2);
                    if (obj.ADM_CODE.Length >= 5)
                        ViewBag.Level2h = obj.ADM_CODE.Substring(0, 5);
                    if (obj.ADM_CODE.Length == 10)
                        ViewBag.Level3h = obj.ADM_CODE.Substring(0, 10);
                }
                else
                {
                    ViewBag.Level1h = null;
                    ViewBag.Level2h = null;
                    ViewBag.Level3h = null;
                }

                obj.GROUP_CODE_OLD = obj.GROUPCODE;
                GetListDVHC(ViewBag.Level1h, ViewBag.Level2h, null);
                return PartialView(obj);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult EditAdminHuyen(EnumeratorModel obj)
        {
            try
            {
                obj.GROUPCODE = "AH";
                if (obj.ADM_CODE.Length == 5)
                {
                    string mtp = obj.ADM_CODE.Substring(0, 2);
                    string mtp2 = obj.ADM_CODE.Substring(2, 3);
                    string areaDownload;
                    if (mtp == MyUser.AdminCode)
                    {
                        using (WebClient wc = new WebClient())
                        {
                            Helper.SetHeaderInfo(wc, "Checkadminunit");
                            wc.Encoding = Encoding.UTF8;
                            //List<ResidentDetailViewModel> residentList = null;
                            //List<SelectListItem> lstItems = new List<SelectListItem>();
                            string UrlPath = string.Format("{0}{1}", enumeratorServiceUrl, "Checkadminunit" + "/" + mtp2 + "/" + mtp + "/" + "2");
                            areaDownload = wc.DownloadString(UrlPath);

                            //return bReturn;
                        }
                        if (areaDownload == "1")
                        {
                            string AdminCode = obj.ADM_CODE;
                            string ENUM_CODE = obj.ENUM_CODE;
                            string FULL_NAME = obj.FULL_NAME;
                            string USERNAME = obj.USERNAME;
                            string GROUPCODE = obj.GROUPCODE;
                            try
                            {
                                using (WebClient wc = new WebClient())
                                {
                                    if (ModelState.IsValid)
                                    {
                                        Helper.SetHeaderInfo(wc, "EditEnumerator");
                                        MemoryStream ms = new MemoryStream();
                                        DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));

                                        serializeUpload.WriteObject(ms, obj);
                                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                                        wc.UploadData(enumeratorServiceUrl + "EditEnumerator", "POST", ms.ToArray());

                                        //UpdateUserGroup(GetData(obj, "A"), wc);
                                        UpdateGroup(GetData(obj, "A"), wc);
                                        UpdateUser(GetData(obj, "A"), wc);

                                        LogStream.Write(MyUser.UserName,
                                           CommonData.AppName,
                                           GetFunction(),
                                           "Cập nhật quản trị huyện - EditAdminHuyen", obj);
                                        ms.Dispose();
                                    }

                                    return Json("Tạo mới thành công", JsonRequestBehavior.AllowGet);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        else
                        {
                            return Json("Có lỗi trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                        }
                    }
                    else
                    {
                        return Json("Có lỗi trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json("Có lỗi trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        #region Edit Admin Tinh
        [HttpGet]
        public ActionResult EditAdminTinh(string EnumID)
        {
            try
            {
                EnumeratorModel obj = GetElementBy(EnumID);
                if (obj.ADM_CODE != null)
                {
                    if (obj.ADM_CODE.Length >= 2)
                        ViewBag.Level1t = obj.ADM_CODE.Substring(0, 2);
                    if (obj.ADM_CODE.Length >= 5)
                        ViewBag.Level2t = obj.ADM_CODE.Substring(0, 5);
                    if (obj.ADM_CODE.Length == 10)
                        ViewBag.Level3t = obj.ADM_CODE.Substring(0, 10);
                }
                else
                {
                    ViewBag.Level1t = null;
                    ViewBag.Level2t = null;
                    ViewBag.Level3t = null;
                }

                obj.GROUP_CODE_OLD = obj.GROUPCODE;
                GetListDVHC(ViewBag.Level1t, null, null);
                return PartialView(obj);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult EditAdminTinh(EnumeratorModel obj)
        {
            try
            {
                obj.GROUPCODE = "AT";
                if (obj.ADM_CODE.Length == 2)
                {
                    string mtp = obj.ADM_CODE.Substring(0, 2);
                    if (mtp == MyUser.AdminCode)
                    {
                        string AdminCode = obj.ADM_CODE;
                        string ENUM_CODE = obj.ENUM_CODE;
                        string FULL_NAME = obj.FULL_NAME;
                        string USERNAME = obj.USERNAME;
                        string GROUPCODE = obj.GROUPCODE;
                        try
                        {
                            using (WebClient wc = new WebClient())
                            {
                                if (ModelState.IsValid)
                                {
                                    Helper.SetHeaderInfo(wc, "EditEnumerator");
                                    MemoryStream ms = new MemoryStream();
                                    DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));

                                    serializeUpload.WriteObject(ms, obj);
                                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                                    wc.UploadData(enumeratorServiceUrl + "EditEnumerator", "POST", ms.ToArray());

                                    //UpdateUserGroup(GetData(obj, "A"), wc);
                                    UpdateGroup(GetData(obj, "A"), wc);
                                    UpdateUser(GetData(obj, "A"), wc);

                                    LogStream.Write(MyUser.UserName,
                                       CommonData.AppName,
                                       GetFunction(),
                                       "Cập nhật quản trị tỉnh - EditAdminTinh", obj);
                                    ms.Dispose();
                                }

                                return Json("Tạo mới thành công", JsonRequestBehavior.AllowGet);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    else
                    {
                        return Json("Có lỗi trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json("Có lỗi trong quá trình xử lý", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult DeleteAdmin(string id)
        {
            try
            {
                EnumeratorModel data = new EnumeratorModel();
                data.ENUMERATOR_ID = id;
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "DeleteEnumerator");
                        data = GetElementBy(id);
                        MemoryStream ms = new MemoryStream();
                        DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(EnumeratorModel));
                        ds.WriteObject(ms, data);
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        wc.UploadData(enumeratorServiceUrl + "DeleteEnumerator", "POST", ms.ToArray());

                        DeleteUserName(data.USERNAME, wc);

                        LogStream.Write(MyUser.UserName,
                           CommonData.AppName,
                           GetFunction(),
                           CommonData.GetListId(new string[] { id })
                           , "Xóa admin - DeleteAdmin");
                        ms.Dispose();
                        return RedirectToAction("SearchAdmin");
                    }

                    return View();

                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult Save(EnumeratorModel obj)
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            ViewBag.ActiveMenus[102] = "active";
            ViewBag.ActiveMenus[108] = "active";
            try
            {
                using (WebClient wc = new WebClient())
                {

                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "AddEnumerator");

                        MemoryStream ms = new MemoryStream();
                        DataContractJsonSerializer serializeUpload = new DataContractJsonSerializer(typeof(EnumeratorModel));
                        obj.ADM_UNIT_ID = MyUser.AdminID;
                        obj.ADM_CODE = MyUser.AdminCode;
                        obj.ENUM_CODE = "123";

                        serializeUpload.WriteObject(ms, obj);
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        byte[] reply = wc.UploadData(enumeratorServiceUrl + "AddEnumerator", "POST", ms.ToArray());
                        string r = System.Text.Encoding.UTF8.GetString(reply);
                        if (String.IsNullOrWhiteSpace(obj.ENUMERATOR_ID))
                        {
                            SaveUserNameToDBAdmin(GetData(obj, "B"), wc);
                        }

                        LogStream.Write(MyUser.UserName,
                           CommonData.AppName,
                           GetFunction()
                           , "Thêm mới cán bộ nghiệp vụ - Save", obj);
                        ms.Dispose();

                        return Json("");
                    }

                    return Json("");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public ActionResult Details()
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            ViewBag.ActiveMenus[102] = "active";
            ViewBag.ActiveMenus[108] = "active";
            try
            {
                List<EnumeratorModel> dataResult = new List<EnumeratorModel>();
                EnumeratorSearchModel info = new EnumeratorSearchModel(MyUser.AdminCode, "", "", "", "", "0", "10");

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "SearchPagingBy");
                    wc.Encoding = Encoding.UTF8;
                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    var jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(info);
                    string jsonResult = wc.UploadString(enumeratorServiceUrl + "SearchPagingBy", "POST", jsonString);
                    dataResult = JsonConvert.DeserializeObjectAsync<List<EnumeratorModel>>(jsonResult).Result;
                }

                ViewBag.Groups = GetGroup();
                ViewBag.ADMIN_CODE = MyUser.AdminCode;
                GetGroupCaption(dataResult);

                return View(dataResult);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult SaveEdit(EnumeratorModel obj)
        {
            try
            {
                EnumeratorModel data = new EnumeratorModel();
                var errors = ModelState.Values.SelectMany(v => v.Errors);
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "EditEnumerator");
                        MemoryStream ms = new MemoryStream();
                        DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(EnumeratorModel));
                        ds.WriteObject(ms, obj);
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        wc.UploadData(enumeratorServiceUrl + "EditEnumerator", "POST", ms.ToArray());

                        //UpdateUserGroup(GetData(obj, "B"), wc);
                        UpdateGroup(GetData(obj, "A"), wc);
                        UpdateUser(GetData(obj, "A"), wc);

                        LogStream.Write(MyUser.UserName,
                          CommonData.AppName,
                          GetFunction()
                          , "Cập nhật cán bộ nghiệp vụ - SaveEdit", obj);
                        ms.Dispose();
                    }
                    return Json(new { ID = obj.ENUMERATOR_ID });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        public ActionResult ViewForDelete(string ENUMERATOR_ID, string Admin)
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[102] = "active";
                ViewBag.ActiveMenus[122] = "active";

                if (Admin != null)
                    ViewBag.Admin = Admin;
                else
                    ViewBag.Admin = null;
                EnumeratorModel obj = GetElementBy(ENUMERATOR_ID);
                ViewBag.Groups = GetGroup();
                List<EnumeratorModel> items = new List<EnumeratorModel>() { obj };
                GetGroupCaption(items);

                return PartialView("ViewForDeletePartail", items[0]);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public JsonResult Delete_Record(EnumeratorSearchModel obj)
        {
            try
            {
                EnumeratorModel data = new EnumeratorModel();
                DeleteInfo info = new DeleteInfo();
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "Delete");
                        data = GetElementBy(obj.ENUMERATOR_ID);
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);
                        string resultString = wc.UploadString(enumeratorServiceUrl + "Delete", "POST", json);
                        info = JsonConvert.DeserializeObjectAsync<DeleteInfo>(resultString).Result;

                        DeleteUserName(data.USERNAME, wc);

                        LogStream.Write(MyUser.UserName,
                          CommonData.AppName,
                          GetFunction(),
                          "Xóa điều tra viên - Delete_Record",
                          obj);
                    }

                    return Json(new
                    {
                        Success = true,
                        Id = obj.ENUMERATOR_ID,
                        RecordCount = info.RecordCount,
                        PageIndex = info.PageIndex
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public JsonResult Delete(string id)
        {
            try
            {
                string a = MyUser.AdminCode;
                bool check = true;

                if (MyUser.GroupCode == "AH")
                {
                    string areaDownload;
                    using (WebClient wc = new WebClient())
                    {
                        Helper.SetHeaderInfo(wc, "Checkadminunit");
                        wc.Encoding = Encoding.UTF8;
                        //List<ResidentDetailViewModel> residentList = null;
                        //List<SelectListItem> lstItems = new List<SelectListItem>();
                        string UrlPath = string.Format("{0}{1}", enumeratorServiceUrl, "Checkadminunit" + "/" + id + "/" + MyUser.AdminCode + "/" + "4");
                        areaDownload = wc.DownloadString(UrlPath);
                        //return bReturn;
                        if (areaDownload == "1")
                        {
                            check = true;
                        }
                        else
                        {
                            check = false;
                        }
                    }
                }
                else
                {
                    if (MyUser.GroupCode == "AT")
                    {
                        string areaDownload;
                        using (WebClient wc = new WebClient())
                        {
                            Helper.SetHeaderInfo(wc, "Checkadminunit");
                            wc.Encoding = Encoding.UTF8;
                            //List<ResidentDetailViewModel> residentList = null;
                            //List<SelectListItem> lstItems = new List<SelectListItem>();
                            string UrlPath = string.Format("{0}{1}", enumeratorServiceUrl, "Checkadminunit" + "/" + id + "/" + MyUser.AdminCode + "/" + "5");
                            areaDownload = wc.DownloadString(UrlPath);
                            //return bReturn;
                            if (areaDownload == "1")
                            {
                                check = true;
                            }
                            else
                            {
                                check = false;
                            }
                        }
                    }
                    else
                    {
                        if (MyUser.GroupCode == "AM")
                        {
                            check = true;
                        }
                    }
                }

                if (check == true)
                {
                    EnumeratorModel data = new EnumeratorModel();
                    data.ENUMERATOR_ID = id;
                    using (WebClient wc = new WebClient())
                    {
                        if (ModelState.IsValid)
                        {
                            Helper.SetHeaderInfo(wc, "DeleteEnumerator");
                            data = GetElementBy(id);
                            MemoryStream ms = new MemoryStream();
                            DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(EnumeratorModel));
                            ds.WriteObject(ms, data);
                            wc.Encoding = Encoding.UTF8;
                            wc.Headers["Content-type"] = "application/json; charset=utf-8";
                            wc.UploadData(enumeratorServiceUrl + "DeleteEnumerator", "POST", ms.ToArray());

                            DeleteUserName(data.USERNAME, wc);

                            LogStream.Write(MyUser.UserName,
                             CommonData.AppName,
                             GetFunction(),
                             CommonData.GetListId(new string[] { id }),
                             "Xóa điều tra viên - Delete");
                            ms.Dispose();
                        }

                        return Json(new { Id = id });

                    }
                }
                else
                {
                    return Json(new { Id = id });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }
        [HttpGet]
        public ActionResult ViewDetail(string ENUMERATOR_ID)
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            ViewBag.ActiveMenus[102] = "active";
            ViewBag.ActiveMenus[108] = "active";
            try
            {
                EnumeratorModel obj = GetElementBy(ENUMERATOR_ID);
                ViewBag.Groups = GetGroup();
                ViewBag.UpdateMode = UpdateMode;
                obj.ADM_CODE = MyUser.AdminCode;
                obj.ADM_UNIT_ID = MyUser.AdminID;
                obj.GROUP_CODE_OLD = obj.GROUPCODE;

                return View(obj);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult SearchResult(EnumeratorSearchModel obj)
        {
            try
            {
                List<EnumeratorModel> dataResult = new List<EnumeratorModel>();
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "SearchPagingBy");
                    wc.Encoding = Encoding.UTF8;
                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    var jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);
                    string jsonResult = wc.UploadString(enumeratorServiceUrl + "SearchPagingBy", "POST", jsonString);
                    dataResult = JsonConvert.DeserializeObjectAsync<List<EnumeratorModel>>(jsonResult).Result;
                    GetGroupCaption(dataResult);

                    return PartialView(dataResult);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public JsonResult CheckForDuplication(string userName)
        {
            try
            {
                bool result = false;
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "Authenthication");
                    string downLoadString = wc.DownloadString(administratorServiceUrl + "Authenthication/Unique" + "/" + userName);
                    result = Convert.ToBoolean(downLoadString);
                }

                // result: true: chua ton tai, nguoc lai da ton tai
                return Json(result);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        public string GetGroupCaption(string code)
        {
            try
            {
                string groupName = "";
                List<EnumeratorModel> items = new List<EnumeratorModel>() { 
                new EnumeratorModel{
                    GROUPCODE = code
                }
            };

                GetGroupCaption(items);
                groupName = items[0].GROUPCODE;

                return groupName;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        #region Quang
        // Quang_16/06/2015 Them const Group, DistricCode, Default Code, vaf Level Code
        private const string Groups = "Groups";
        private const string DISTRICT_CODE = "DISTRICT_CODE";
        private const string DEFAULT_CODE = "-1";
        private const string LEVEL_DEFAULT = "1";
        #endregion
        #region private method

        private void SaveUserName(USER_GROUP_CREATE data, WebClient wc)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(USER_GROUP_CREATE));
                serializer.WriteObject(ms, data);
                wc.Headers["Content-type"] = "application/json; charset=utf-8";
                wc.UploadData(administratorServiceUrl + "Register", "POST", ms.ToArray());
                ms.Dispose();
            }
            catch
            {
                throw;
            }
        }

        private void SaveUserNameToDBAdmin(USER_GROUP_CREATE data, WebClient wc)
        {
            try
            {
                using (WebClient wcf = new WebClient())
                {
                    data.AppCode = CommonData.AppCode;
                    MemoryStream ms = new MemoryStream();
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(USER_GROUP_CREATE));
                    serializer.WriteObject(ms, data);
                    wcf.Headers["Content-type"] = "application/json; charset=utf-8";
                    Helper.SetHeaderInfo(wcf, "RegisterUser");
                    wcf.UploadData(administratorServiceUrl + "RegisterUser", "POST", ms.ToArray());
                    ms.Dispose();
                }
            }
            catch
            {
                throw;
            }
        }

        private void UpdateUserGroup(USER_GROUP_CREATE data, WebClient wc)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(USER_GROUP_CREATE));
                serializer.WriteObject(ms, data);
                wc.Headers["Content-type"] = "application/json; charset=utf-8";
                wc.UploadData(administratorServiceUrl + "UserInGroupUpdate", "POST", ms.ToArray());
                ms.Dispose();
            }
            catch
            {
                throw;
            }
        }

        private void UpdateGroup(USER_GROUP_CREATE data, WebClient wc)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(USER_GROUP_CREATE));
                serializer.WriteObject(ms, data);
                wc.Headers["Content-type"] = "application/json; charset=utf-8";
                wc.UploadData(administratorServiceUrl + "UpdateUserInGroup", "POST", ms.ToArray());
                ms.Dispose();
            }
            catch
            {
                throw;
            }
        }

        private void UpdateUser(USER_GROUP_CREATE data, WebClient wc)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(USER_GROUP_CREATE));
                serializer.WriteObject(ms, data);
                wc.Headers["Content-type"] = "application/json; charset=utf-8";
                wc.UploadData(administratorServiceUrl + "UpdateUser", "POST", ms.ToArray());
                ms.Dispose();
            }
            catch
            {
                throw;
            }
        }

        private bool DeleteUserName(string userName, WebClient wc)
        {
            try
            {
                wc.Encoding = Encoding.UTF8;
                wc.Headers["Content-type"] = "application/json; charset=utf-8";
                string result = wc.DownloadString(administratorServiceUrl + "deleteUser" + "/" + userName + "/" + CommonData.AppCode);

                return Convert.ToBoolean(result);
            }
            catch
            {
                throw;
            }
        }

        private USER_GROUP_CREATE GetData(EnumeratorModel obj, string type)
        {
            USER_GROUP_CREATE item = new USER_GROUP_CREATE();
            item.AppCode = "TKTHDS.PM2";
            item.Type = type;
            item.UserName = obj.USERNAME;
            item.GroupCode = obj.GROUPCODE;
            item.GroupCodeOld = obj.GROUP_CODE_OLD;
            item.FullName = obj.FULL_NAME;
            item.Email = obj.EMAIL;

            return item;
        }

        private void GetGroupCaption(List<EnumeratorModel> data)
        {
            List<GroupModel> groupItems = GetGroupModel();
            foreach (var d in data)
            {
                foreach (var g in groupItems)
                {
                    if (d.GROUPCODE == g.GroupCode)
                    {
                        d.GROUPCODE = g.GroupName;
                        break;
                    }
                }
            }
        }

        private EnumeratorModel GetElementBy(string id)
        {
            try
            {
                EnumeratorModel obj = new EnumeratorModel();
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetById");
                    wc.Encoding = Encoding.UTF8;
                    string downLoadString = wc.DownloadString(enumeratorServiceUrl + "GetById" + "/" + id.ToString());
                    obj = JsonConvert.DeserializeObjectAsync<EnumeratorModel>(downLoadString).Result;
                }

                return obj;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        private List<SelectListItem> GetGroup()
        {
            List<SelectListItem> groupItems = new List<SelectListItem>();
            groupItems.Add(new SelectListItem()
            {
                Text = "Chọn nhóm",
                Value = ""
            });
            try
            {
                List<GroupModel> items = GetGroupModel();
                List<GroupModel> groups = FilterGroup(items);
                foreach (GroupModel g in groups)
                {
                    groupItems.Add(new SelectListItem
                    {
                        Text = g.GroupName,
                        Value = g.GroupCode
                    });
                }

                return groupItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        private void FilterGroup(List<GroupModel> groups, params string[] filter)
        {
            for (int j = 0; j < groups.Count(); j++)
            {
                for (int i = 0; i < filter.Length; i++)
                {
                    if (groups[j].GroupCode.Trim().ToUpper() == filter[i].Trim().ToUpper())
                    {
                        groups.RemoveAt(j);
                        j--;
                        break;
                    }
                }
            }
        }

        private List<GroupModel> FilterGroup(List<GroupModel> groups)
        {
            string[] filter = new string[] { "TT", "BK", "VE", "DT", "NL" };
            List<GroupModel> items = new List<GroupModel>();
            for (int j = 0; j < groups.Count(); j++)
            {
                for (int i = 0; i < filter.Length; i++)
                {
                    if (groups[j].GroupCode.Trim().ToUpper() == filter[i].Trim().ToUpper())
                    {
                        items.Add(groups[j]);
                        break;
                    }
                }
            }

            return items;
        }

        private List<GroupModel> GetGroupModel()
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GroupGetAll");
                    wc.Encoding = Encoding.UTF8;
                    string downloadString = wc.DownloadString(administratorServiceUrl + "GroupGetAll" + "/" + "TKTHDS.PM2");
                    List<GroupModel> dataServer = JsonConvert.DeserializeObjectAsync<List<GroupModel>>(downloadString).Result;

                    return dataServer;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        private void GetAdminisUnitName(string id)
        {
            ViewBag.AdminisUnitName = "Dia ban hanh chinh";
        }

        #endregion
        #region Bind dia ban hanh chinh Tinh/Huyen/Xa

        #region Quang: Edit cach lay danh sach ma don vi hanh chinh

        private List<AdminisUnitModel> BindAdminUnit_Q(string parentCode, string level)
        {
            try
            {
                List<AdminisUnitModel> adminList = new List<AdminisUnitModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByIdParentTablet");
                    wc.Encoding = Encoding.UTF8;
                    string url = adminUnitServiceUrl + "GetByIdParentTablet" + "/" + parentCode + "/" + level;
                    string adminDownload = wc.DownloadString(url);
                    adminList = JsonConvert.DeserializeObjectAsync<List<AdminisUnitModel>>(adminDownload).Result;
                    return adminList;
                }
            }
            catch
            {
                throw;
            }
        }
        private List<SelectListItem> BindDropDownList(List<AdminisUnitModel> adminList)
        {
            List<SelectListItem> lstItems = new List<SelectListItem>();
            if (adminList == null)
            {
                lstItems.Add(new SelectListItem
                {
                    Text = "Chọn đơn vị hành chính",
                    Value = ""
                });
            }
            else
            {
                lstItems.Add(new SelectListItem
                {
                    Text = "Chọn đơn vị hành chính",
                    Value = ""
                });
                try
                {
                    foreach (var ad in adminList)
                    {
                        if (ad != null)
                        {
                            lstItems.Add(new SelectListItem
                            {
                                Value = ad.CODE,
                                Text = ad.ADM_NAME
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return lstItems;
        }

        private void GetListDVHC(string tCode, string hCode, string xCode)
        {
            try
            {
                if (tCode != null)
                    ViewBag.ListTinhSelected = setValueSelected(BindAdminUnit_Q("-1", "1"), tCode);
                if (tCode != null && hCode != null)
                    ViewBag.ListHuyenSelected = setValueSelected(BindAdminUnit_Q(tCode, "2"), hCode);
                if (tCode != null && hCode != null && xCode != null)
                    ViewBag.ListXaSelected = setValueSelected(BindAdminUnit_Q(hCode, "3"), xCode);
            }
            catch
            {
                throw;
            }
        }

        private void ListTinh()
        {
            try
            {
                ViewBag.ListTinh = BindDropDownList(BindAdminUnit_Q("-1", "1"));
                ViewBag.ListHuyen = BindDropDownList(null);
                ViewBag.ListXa = BindDropDownList(null);
            }
            catch
            {
                throw;
            }
        }


        private void ListHuyen()
        {
            try
            {
                string pCode = MyUser.AdminCode;
                ViewBag.ListHuyen = BindDropDownList(BindAdminUnit_Q(pCode, "2"));
                ViewBag.ListXa = BindDropDownList(null);
                ViewBag.ListTinhSelected = setValueSelected(BindAdminUnit_Q("-1", "1"), pCode);
            }
            catch
            {
                throw;
            }
        }

        private void ListXa()
        {
            try
            {
                string pCode = MyUser.AdminCode;
                string TCode = GetParentCode(MyUser.AdminCode)[1];
                ViewBag.ListXa = BindDropDownList(BindAdminUnit_Q(pCode, "3"));
                ViewBag.ListTinhSelected = setValueSelected(BindAdminUnit_Q("-1", "1"), TCode);
                ViewBag.ListHuyenSelected = setValueSelected(BindAdminUnit_Q(TCode, "2"), pCode);
            }
            catch
            {
                throw;
            }
        }

        private Dictionary<int, string> GetParentCode(string ADM_CODE)
        {
            Dictionary<int, string> Code = new Dictionary<int, string>();
            if (ADM_CODE != null)
            {
                if (ADM_CODE.Length >= 2)
                    Code.Add(1, ADM_CODE.Substring(0, 2));
                if (ADM_CODE.Length >= 5)
                    Code.Add(2, ADM_CODE.Substring(0, 5));
                if (ADM_CODE.Length == 10)
                    Code.Add(3, ADM_CODE.Substring(0, 10));
            }
            else
            {
                Code.Add(1, null);
                Code.Add(2, null);
                Code.Add(3, null);
            }
            return Code;
        }

        public List<SelectListItem> setValueSelected(List<AdminisUnitModel> adminList, string value)
        {
            try
            {
                List<SelectListItem> list = BindDropDownList(adminList);
                foreach (var item in list)
                {
                    if (item.Value.Equals(value))
                    {
                        item.Selected = true;
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        #endregion

        public SelectList BindAdminUnit(string parentCode, string level)
        {
            try
            {
                List<AdminisUnitModel> adminList = new List<AdminisUnitModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByIdParentTablet");
                    wc.Encoding = Encoding.UTF8;
                    List<SelectListItem> lstItems = new List<SelectListItem>();
                    string url = adminUnitServiceUrl + "GetByIdParentTablet" + "/" + parentCode + "/" + level;
                    string adminDownload = wc.DownloadString(url);
                    adminList = JsonConvert.DeserializeObjectAsync<List<AdminisUnitModel>>(adminDownload).Result;
                    foreach (var ad in adminList)
                    {
                        if (ad != null)
                            lstItems.Add(new SelectListItem
                            {
                                Value = ad.CODE,
                                Text = ad.ADM_NAME
                            });
                    }
                    return new SelectList(lstItems, "Value", "Text");

                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        [AjaxValidateAntiForgeryToken]
        public JsonResult ddlAdmUnitLevel1()
        {
            try
            {
                return Json(BindAdminUnit("-1", "1"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        [AjaxValidateAntiForgeryToken]
        public JsonResult ddlAdmUnitLevel2(string parentCode)
        {
            try
            {
                return Json(BindAdminUnit(parentCode, "2"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        [AjaxValidateAntiForgeryToken]
        public JsonResult ddlAdmUnitLevel3(string parentCode)
        {
            try
            {
                return Json(BindAdminUnit(parentCode, "3"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        #region export excel Enum
        public System.Data.DataTable ConvertToDataTable<T>(IList<T> data)
        {
            try
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

                System.Data.DataTable table = new System.Data.DataTable();

                foreach (PropertyDescriptor prop in properties)
                    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

                foreach (T item in data)
                {
                    DataRow row = table.NewRow();

                    foreach (PropertyDescriptor prop in properties)
                        row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

                    table.Rows.Add(row);
                }
                return table;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        public FileResult ExportData(string GROUP_CODE, string FULL_NAME, string USERNAME, string ENUM_CODE)
        {
            try
            {
                EnumeratorSearchModel search = new EnumeratorSearchModel();
                search.ENUMERATOR_ID = "";
                search.ADMINIS_UNIT_ID = MyUser.AdminID;
                search.ADMIN_CODE = MyUser.AdminCode;
                search.FULL_NAME = FULL_NAME;
                search.USERNAME = USERNAME;
                search.GROUPCODE = GROUP_CODE;
                search.PAGE_INDEX = 0.ToString();
                search.PAGE_SIZE = 1000.ToString();
                string TenDB = MyUser.AdminName;
                List<EnumeratorModel> EnumList = new List<EnumeratorModel>();
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "SearchPagingBy");
                    wc.Encoding = Encoding.UTF8;
                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(search);
                    string EnumDownload = wc.UploadString(enumeratorServiceUrl + "SearchPagingBy", "POST", json);
                    EnumList = JsonConvert.DeserializeObjectAsync<List<Models.EnumeratorModel>>(EnumDownload).Result;
                }

                GetGroupCaption(EnumList);

                //tao ra 1 list moi khi muon lay mot so cot nhat dinh
                var list = new List<Tuple<string, string, string, string>>();


                foreach (EnumeratorModel h in EnumList)
                {
                    try
                    {
                        list.Add(Tuple.Create(h.FULL_NAME
                                            , h.USERNAME
                                            , h.GROUPCODE
                                            , h.DESCRIPTIONS
                                         )
                            );
                    }
                    catch { ;}
                }

                //in ra file excel
                DataTable dt = ConvertToDataTable(list);

                using (var excelPackage = new ExcelPackage())
                {
                    excelPackage.Workbook.Properties.Author = "MR. Quy";
                    excelPackage.Workbook.Properties.Title = "Export excel";
                    var sheet = excelPackage.Workbook.Worksheets.Add("Cán bộ nghiệp vụ");
                    // output a line for the headers
                    sheet.Name = "NhanVienDT";
                    // all indexes start at 1                    
                    sheet.Cells["A1"].Value = "Thông tin cán bộ nghiệp vụ";
                    sheet.Cells["A1:E1"].Merge = true;
                    sheet.Cells["A1:E1"].Style.Font.Size = 18;
                    sheet.Cells["A1:E"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    sheet.Cells["A1:E1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    sheet.Cells["A1:E1"].Style.Font.Bold = true;
                    sheet.Cells["A1:E1"].Style.WrapText = true;

                    DataTable table = new DataTable();
                    table.Columns.Add("STT", typeof(string));

                    for (int i = 1; i <= dt.Rows.Count; i++)
                    {
                        DataRow row = table.NewRow();
                        row["STT"] = i;
                        table.Rows.Add(row);
                    }

                    using (var rng = sheet.Cells["A2:E2"])
                    {
                        rng.Style.Font.Bold = true;
                        rng.Style.WrapText = true;
                        rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        rng.Style.Font.Size = 9;
                    }

                    sheet.Cells["A2"].Value = "(" + TenDB + ")";
                    sheet.Cells["A2:E2"].Merge = true;
                    sheet.Cells["A2:E2"].Style.Font.Size = 10;
                    sheet.Cells["A2:E2"].Style.Font.Color.SetColor(Color.Red);
                    sheet.Cells["A2:E2"].Style.Font.Bold = true;
                    sheet.Cells["A2:E2"].Style.WrapText = true;

                    sheet.Cells["A4"].Value = "STT";
                    sheet.Cells["A4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    sheet.Cells["B4"].Value = "Họ Tên";
                    sheet.Cells["C4"].Value = "Tên đăng nhập";
                    sheet.Cells["D4"].Value = "Nhóm";
                    sheet.Cells["E4"].Value = "Mô tả";

                    sheet.Cells["A4:E4"].Style.Font.Size = 12;
                    sheet.Cells["A4:E4"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    sheet.Cells["A4:E4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    sheet.Cells["A4:E4"].Style.Font.Bold = true;

                    sheet.Cells["B5"].LoadFromDataTable(dt, true);
                    sheet.Cells["A5"].LoadFromDataTable(table, true);
                    sheet.DeleteRow(5);

                    for (var j = 0; j < dt.Columns.Count + 1; j++)
                    {
                        for (var i = 0; i <= dt.Rows.Count; i++)
                        {
                            sheet.Cells[i + 4, j + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                            sheet.Cells[i + 4, j + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                            sheet.Cells[i + 4, j + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                            sheet.Cells[i + 4, j + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                        }
                    }

                    sheet.Cells["A1:AN"].AutoFitColumns();
                    sheet.Cells["B1:BN"].AutoFitColumns();
                    sheet.Cells["C1:CN"].AutoFitColumns();
                    sheet.Cells["D1:DN"].AutoFitColumns();
                    sheet.Cells["E1:EN"].AutoFitColumns(30, 70);

                    sheet.Column(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

                    sheet.Column(1).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    sheet.Column(2).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    sheet.Column(3).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    sheet.Column(4).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    sheet.Column(5).Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                    sheet.Column(5).Style.WrapText = true;

                    MemoryStream stream = new MemoryStream();
                    ZipOutputStream zipstream = new ZipOutputStream(stream);
                    zipstream.SetLevel(3); //0-9, 9 being the highest level of compression

                    // loops through the PDFs I need to create
                    var newEntry = new ZipEntry("DSCanBoNghiepVu.xlsx"); //vanduong, 16/7/2015
                    newEntry.DateTime = DateTime.Now;
                    zipstream.PutNextEntry(newEntry);
                    MemoryStream inStream = new MemoryStream(excelPackage.GetAsByteArray());
                    StreamUtils.Copy(inStream, zipstream, new byte[4096]);
                    inStream.Close();
                    zipstream.CloseEntry();

                    zipstream.IsStreamOwner = false;
                    zipstream.Close();
                    stream.Position = 0;

                    return File(stream.ToArray(), "application/octet-stream", "DSCanBoNghiepVu-" + TenDB + "-.zip");
                    stream.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        public ActionResult print(string GROUP_CODE, string FULL_NAME, string USERNAME, string ENUM_CODE)
        {
            try
            {
                EnumeratorSearchModel search = new EnumeratorSearchModel();
                search.ENUMERATOR_ID = "";
                search.ADMINIS_UNIT_ID = MyUser.AdminID;
                search.ADMIN_CODE = MyUser.AdminCode;
                search.FULL_NAME = FULL_NAME;
                search.USERNAME = USERNAME;
                search.GROUPCODE = GROUP_CODE;
                search.PAGE_INDEX = 0.ToString();
                search.PAGE_SIZE = 1000.ToString();
                string TenDB = MyUser.AdminName;
                ViewBag.TenDB = TenDB;

                List<EnumeratorModel> EnumList = new List<EnumeratorModel>();
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "SearchPagingBy");
                    wc.Encoding = Encoding.UTF8;

                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(search);
                    string EnumDownload = wc.UploadString(enumeratorServiceUrl + "SearchPagingBy", "POST", json);
                    EnumList = JsonConvert.DeserializeObjectAsync<List<Models.EnumeratorModel>>(EnumDownload).Result;
                }
                GetGroupCaption(EnumList);
                ViewBag.rows = EnumList;

            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }

            return View();
        }
        #endregion

        private string GetFunction()
        {
            return "Quản lý người dùng - EnumeratorController";
        }

        [HttpPost]
        public JsonResult CheckEmail(string EMAIL)
        {
            try
            {
                bool result = false;
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "CheckEmail");
                    string downLoadString = wc.DownloadString(administratorServiceUrl + "CheckEmail" + "/" + EMAIL + "/" + CommonData.AppCode);
                    result = Convert.ToBoolean(downLoadString);
                }

                if (result == false)
                {
                    return Json("Mail đã tồn tại trong hệ thống");
                }
                else
                    return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult AccountChangePass()
        {
            try
            {
                ViewBag.ExceptionPass = WebConfigurationManager.AppSettings["ExceptionPass"];
                return View();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public JsonResult SaveChangePass(string PassWord)
        {
            try
            {
                bool exits = false;
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "ChangePassUser");
                    string BoolChangePass = wc.DownloadString(administratorServiceUrl + "ChangePassUser" + "/" + PassWord + "/" + MyUser.UserName + "/" + CommonData.AppCode);
                    exits = Convert.ToBoolean(BoolChangePass);
                }
                return Json(exits, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckPassUserName(string PassWord)
        {
            try
            {
                bool exits = false;
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "CheckPassUserName");
                    string BoolChangePass = wc.DownloadString(administratorServiceUrl + "CheckPassUserName" + "/" + PassWord + "/" + MyUser.UserName + "/" + CommonData.AppCode);
                    exits = Convert.ToBoolean(BoolChangePass);
                }
                return Json(exits, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        private void StandardData(EnumeratorModel obj)
        {
            if (obj == null) return;

            obj.FULL_NAME = obj.FULL_NAME != null ? obj.FULL_NAME.Trim() : obj.FULL_NAME;
            obj.EMAIL = obj.EMAIL != null ? obj.EMAIL.Trim() : obj.EMAIL;
            obj.DESCRIPTIONS = obj.DESCRIPTIONS != null ? obj.DESCRIPTIONS.Trim() : obj.DESCRIPTIONS;
        }
    }

    public class DeleteInfo
    {
        public int PageIndex { get; set; }
        public int RecordCount { get; set; }

        public DeleteInfo()
        {
            PageIndex = 0;
            RecordCount = 0;
        }
    }
}